package com.cal2sync;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

public class display_rules extends Activity{
	LinearLayout l;
	int pos;
	ListView list_view;
	
	@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.display_rules);
	        
	        list_view = (ListView) findViewById(R.id.rulelist);
	        l=(LinearLayout) findViewById(R.id.main);
	        
	        /*Display rules in list*/
	        
	        HttpClient httpclient = new DefaultHttpClient();
			//HttpPost httppost = new HttpPost("http://10.0.2.2/display_rules.php");
			HttpPost httppost = new HttpPost("http://192.168.16.1/display_rules.php");

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
				nameValuePairs.add(new BasicNameValuePair("username", GlobalData.username));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);
				Reader in = new BufferedReader(
				        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
				    StringBuilder builder= new StringBuilder();
				    char[] buf = new char[1000];
				    int l = 0;
				    while (l >= 0) {
				        builder.append(buf, 0, l);
				        l = in.read(buf);
				    }
				System.out.println("Response ->"+builder.toString());
				HashMap<String,String> res = parse(builder.toString());
				System.out.println(res);
				String[] rule_created = new String[res.size()];
				int cnt=0;
				for(String temp: res.keySet())
				{
					String curr;
					rule_created[cnt++] = "Event :"+temp+"\n"+"Rule :"+res.get(temp);
				}
				list_view.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, rule_created));
				
			}
			catch (ClientProtocolException e) {
				System.out.println("exception 1");
				// TODO Auto-generated catch block
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("error ");
				// TODO Auto-generated catch block
			}
	        
	        
	        final Animation inslide =AnimationUtils.loadAnimation(this, R.anim.lefttoright);
			final Animation slide = AnimationUtils.loadAnimation(this, R.anim.righttoleft);

			l.startAnimation(inslide);
			inslide.setFillAfter(true);
			inslide.setAnimationListener(new AnimationListener(){
				public void onAnimationEnd(Animation animation){
	        
					list_view.setOnItemClickListener(new AdapterView.OnItemClickListener()
					{
						
						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							// TODO Auto-generated method stub
							pos=arg2;
							l.startAnimation(slide);
							slide.setFillAfter(true);
							slide.setAnimationListener(new AnimationListener(){
								public void onAnimationEnd(Animation animation){
									System.out.println(list_view.getItemAtPosition(pos).toString());
									String[] temp;
									String event=new String();
									String action=new String();
									 String delimiter = "\\n";
									 String delimiter2 = ":";
									 String[] temp2;
									  /* given string will be split by the argument delimiter provided. */
									  temp = list_view.getItemAtPosition(pos).toString().split(delimiter);
									  /* print substrings */
									  for(int i =0; i < temp.length ; i++)
									  {
										  temp2 = temp[i].split(delimiter2);
										  System.out.println("temp2 ->"+temp2[temp2.length-1]);
										  if(i==0)
											  event=temp2[temp2.length-1];
										  else if(i==1)
											  action =temp2[temp2.length-1];
											  
									  }
									  Intent i = new Intent(getBaseContext(),update_rule.class);
									  i.putExtra("event", event);
									  i.putExtra("action", action);
			        				  startActivity(i);
								}

								@Override
								public void onAnimationRepeat(Animation arg0) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onAnimationStart(Animation animation) {
									// TODO Auto-generated method stub

								}
							});
							
							
						}
					});
					
					
	        final Button button1 = (Button) findViewById(R.id.create_new_rule_btn);
	        button1.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                // Perform action on click
	            	l.startAnimation(slide);
					slide.setFillAfter(true);
					slide.setAnimationListener(new AnimationListener(){
						public void onAnimationEnd(Animation animation){
							
							Intent i = new Intent(getBaseContext(),create_rule.class);
        					startActivity(i);
						}

						@Override
						public void onAnimationRepeat(Animation arg0) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}
					});
	            }
	        });
	        
				
			
			
			 final Button button2 = (Button) findViewById(R.id.done_btn);
		        button2.setOnClickListener(new View.OnClickListener() {
		            public void onClick(View v) {
		                // Perform action on click
		            	l.startAnimation(slide);
						slide.setFillAfter(true);
						slide.setAnimationListener(new AnimationListener(){
							public void onAnimationEnd(Animation animation){
								Intent i = new Intent(getBaseContext(),last_screen.class);
	        					startActivity(i);
							}

							@Override
							public void onAnimationRepeat(Animation arg0) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onAnimationStart(Animation animation) {
								// TODO Auto-generated method stub

							}
						});
		            }
		        });
		        
					}

					@Override
					public void onAnimationRepeat(Animation arg0) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationStart(Animation animation) {
						// TODO Auto-generated method stub

					}
				});
	 }
	 
	 HashMap<String,String> parse(String result)
	 {
		 System.out.println("result ->"+result);
		 HashMap<String,String> res_map = new HashMap<String,String>();
		 String[] temp;
		 String delimiter = ";";
		 String delimiter2= ",";
		 String[] temp2;
		  /* given string will be split by the argument delimiter provided. */
		  temp = result.split(delimiter);
		  /* print substrings */
		  for(int i =0; i < temp.length ; i++)
		  {
			  temp2 = temp[i].split(delimiter2);
			  temp2[0]=temp2[0].replace("{","");
			  temp2[1]=temp2[1].replace("}","");
			  res_map.put(temp2[0], temp2[1]);
		  }
		 
		 
		return res_map;
	 	
	 }

}


